package cn.clq.basic.interceptor;

import cn.clq.basic.annotation.PreAuthorize;
import cn.clq.basic.constant.Constant;
import cn.clq.basic.util.jwt.JwtUtils;
import cn.clq.basic.util.jwt.LoginSuccessDto;
import cn.clq.basic.util.jwt.Playload;
import cn.clq.basic.util.jwt.RsaUtils;
import cn.clq.system.mapper.PermissionMapper;
import cn.clq.user.domain.Logininfo;
import cn.clq.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.clq.basic.util.jwt.JwtUtils.getInfoFromToken;

/**
 * @author clqlongbao
 * @version 1.0
 * @description: 登录拦截器
 * @date 2022/6/18 23:45
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //2.token有值说明登陆成功，判断权限
        if(StringUtils.hasLength(token)){
//            Object logininfoTmp = redisTemplate.opsForValue().get(token);
            //3.获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //4.使用公钥解密jwt串
            Playload<LoginSuccessDto> playload = getInfoFromToken(token, publicKey, LoginSuccessDto.class);
            LoginSuccessDto loginSuccessDto = playload.getUserInfo();
            if(loginSuccessDto!=null){
                //5.校验是否是员工，员工校验相应权限，用户直接放行
                Logininfo logininfo = loginSuccessDto.getLogininfo();
                if(logininfo.getType()== Constant.PersionType.EMPLOYEE){
                    //6.拿到当前请求的方法
                    HandlerMethod method = (HandlerMethod) handler;
                    //7.校验方法上是否有@PreAuthorize注解
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if(annotation!=null){
                        //8.拿到本次请求的sn
                        String name = annotation.name();//name
                        String value = annotation.value();//sn
//                        //5.查出当前登陆人在数据库里面的权限
//                        List<String> allSn = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //9判断该员工的所有权限中，是否有本次请求的sn
                        if(!loginSuccessDto.getPermissions().contains(value)){
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                //登陆了,刷新过期时间并放行
//                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //10.拦截请求，让用户去登录
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        //拦截请求
        return false;
    }
}
